<template>
  <el-card>
    <el-form :model="listQuery" inline @submit.native.prevent>
      <el-form-item>
        <el-input
          v-model="listQuery.roleName"
          placeholder="按名称查找"
          clearable
          @keyup.enter.native="handleFilter"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button v-has-perm="['role:add']" type="primary" icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="listLoading" :data="list" highlight-current-row>
      <el-table-column
        label="序号"
        align="center"
        type="index"
        width="60"
        :index="(listQuery.pageIndex - 1) * listQuery.pageSize + 1"
      />
      <el-table-column label="角色名称" align="center" prop="roleName" />
      <el-table-column label="角色编码" align="center" prop="roleKey" />
      <el-table-column label="显示顺序" align="center" prop="roleSort" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="更新时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center">
        <template v-slot="{ row }">
          <el-button v-has-perm="['role:edit']" size="mini" type="text" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-has-perm="['role:delete']" size="mini" type="text" @click="handleDelete(row.roleId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageIndex"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogVisible" width="500px"
      :close-on-click-modal="false"
      @closed="clearTree">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="temp.roleName" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleKey">
          <el-input v-model="temp.roleKey" placeholder="角色编码" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input-number v-model="temp.roleSort" placeholder="显示顺序" controls-position="right" />
        </el-form-item>
      </el-form>
      <div class="tree-header">
        <div class="label">菜单权限</div>
        <el-button @click="handleCheckAll" size="mini">全选</el-button>
        <el-button @click="clearTree" size="mini">清空</el-button>
      </div>
      <div class="tree-bg">
        <el-tree
          ref="tree"
          node-key="menuId"
          :data="menuTree"
          :props="treeProps"
          show-checkbox
          :default-expand-all="expand"
          v-loading="treeLoading"
          @check-change="handleCheckChange">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import Pagination from "@/components/Pagination/index"
import RoleApi from "@/api/RoleApi"
import MenuApi from "@/api/MenuApi"

export default {
  name: "RolePage",
  components: { Pagination },
  data() {
    return {
      list: [],
      menuTree: [],
      menuList: [],
      menuIds: [],
      total: 0,
      expand: true,
      listLoading: true,
      treeLoading: false,
      listQuery: {
        pageIndex: 1,
        pageSize: 10
      },
      textMap: {
        update: "编辑",
        create: "新增"
      },
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "角色编码不能为空", trigger: "blur" }
        ]
      },
      dialogStatus: "",
      temp: {},
      treeProps: {
        label: "menuName"
      },
      dialogVisible: false
    }
  },
  created() {
    this.getTree()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      RoleApi.page(this.listQuery).then(result => {
        this.list = result.data
        this.total = result.total
        this.listLoading = false
      })
    },
    getTree() {
      MenuApi.listAndTree().then(result => {
        let menuList = result.data[0].list
        this.menuTree = result.data[0].tree
        this.menuList = menuList
        this.menuIds = menuList.map(i => i.menuId)
      })
    },
    getChecked() {
      this.treeLoading = true
      RoleApi.checked(this.temp.roleId).then(result => {
        this.$refs.tree.setCheckedKeys(result.data)
      }).finally(() => this.treeLoading = false)
    },
    resetTemp() {
      this.temp = {
        name: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = "create"
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate()
      })
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          RoleApi.save(this.temp).then(() => {
            this.$message.success("添加成功！")
            this.getList()
            this.dialogVisible = false
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = "update"
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate()
        this.getChecked()
      })
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          RoleApi.update(this.temp).then(() => {
            this.dialogVisible = false
            this.getList()
            this.$message.success("修改成功！")
          })
        }
      })
    },
    handleDelete(id) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        RoleApi.delete(id).then(() => {
          this.dialogVisible = false
          this.$message.success("操作成功！")
        })
      })
    },
    handleCheckChange() {
      this.temp.menuIds = this.$refs.tree.getCheckedKeys(true)
    },
    handleCheckAll() {
      this.$refs.tree.setCheckedKeys(this.menuIds)
    },
    clearTree() {
      this.$refs.tree && this.$refs.tree.setCheckedKeys([])
    },
    handleFilter() {
      this.listQuery.pageIndex = 1
      this.getList()
    }
  }
}
</script>
<style lang="scss">
.tree-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  font-size: 14px;
  color: #606266;
  font-weight: bold;
  width: 80px;
  text-align: right;
  padding-right: 12px;
  line-height: 40px;
}

.tree-bg {
  border: 1px solid #e5e5e5;
  padding: 5px;
  overflow-y: auto;
  max-height: 30vh;
  margin-left: 80px;
}
</style>
